package controllers

import (
	"encoding/base64"
	"fmt"
	"github.com/beego/beego/v2/adapter/logs"
	"github.com/beego/beego/v2/client/orm"
	utils "github.com/beego/beego/v2/core/utils"
	beego "github.com/beego/beego/v2/server/web"
	"github.com/gomodule/redigo/redis"
	"project/models"
	"regexp"
	"strconv"
)

type UserController struct {
	beego.Controller
}

// ShowReg 显示注册页面
func (this *UserController) ShowReg() {
	this.TplName = "register.html"
}

// HandleReg 处理注册数据
func (this *UserController) HandleReg() {
	// 获取数据
	userName := this.GetString("user_name")
	pwd := this.GetString("pwd")
	cpwd := this.GetString("cpwd")
	email := this.GetString("email")
	// 数据校验
	if userName == "" || pwd == "" || cpwd == "" || email == "" {
		this.Data["error"] = "数据不完整，请重新输入"
		this.TplName = "register.html"
		return
	}

	if pwd != cpwd {
		this.Data["error"] = "两次输入密码不一致，请重新注册"
		this.TplName = "register.html"
		return
	}
	logs.Info(email)
	reg, _ := regexp.Compile(`[\w\.]+@\w+\.[a-z]{2,3}(\.[a-z]{2,3})?`)
	res := reg.FindString(email)
	if res == "" {
		this.Data["error"] = "邮箱格式不正确"
		this.TplName = "register.html"
		return
	}
	// 处理数据
	o := orm.NewOrm()
	var user models.User
	user.Name = userName
	user.PassWord = pwd
	user.Email = email

	_, err := o.Insert(&user)
	if err != nil {
		this.Data["error"] = "注册失败，请重新注册"
		this.TplName = "register.html"
		return
	}
	// 发送邮件
	emailConfig := `{"username":"348544801@qq.com","password":"ziaqrxvzoohlbjeb","host":"smtp.qq.com","port":587}`
	emailConn := utils.NewEMail(emailConfig)
	emailConn.From = "348544801@qq.com"
	emailConn.To = []string{email}
	emailConn.Subject = "在线商城用户注册"
	// 注意发送给用户的是激活请求地址
	emailConn.Text = "localhost:8081/active?id=" + strconv.Itoa(user.Id)
	err = emailConn.Send()
	if err != nil {
		this.Data["error"] = "邮件发送失败"
		this.TplName = "register.html"
		fmt.Println("err:", err)
		return
	}

	// 返回视图
	this.Ctx.WriteString("注册成功，请激活用户!")
}

// ActiveUser 激活处理
func (this *UserController) ActiveUser() {
	// 获取数据
	id, err := this.GetInt("id")
	// 校验数据
	if err != nil {
		this.Data["error"] = "要激活的用户不存在"
		this.TplName = "register.html"
		return
	}
	// 处理数据
	o := orm.NewOrm()
	var user models.User
	user.Id = id
	// 更新之前做查询操作，默认以id为字段查询
	err = o.Read(&user)
	if err != nil {
		this.Data["error"] = "要激活的用户不存在"
		this.TplName = "register.html"
		return
	}
	user.Active = true
	o.Update(&user)
	// 返回视图，地址栏会改变，所以使用Redirect
	this.Redirect("/login", 302)
}

// ShowLogin 展示登录页面
func (this *UserController) ShowLogin() {
	userName := this.Ctx.GetCookie("userName")
	// 解码
	temp, _ := base64.StdEncoding.DecodeString(userName)
	if string(temp) == "" {
		this.Data["userName"] = ""
		this.Data["checked"] = ""
	} else {
		this.Data["userName"] = string(temp)
		this.Data["checked"] = "checked"
	}
	this.TplName = "login.html"
}

// HandleLogin 处理登录业务
func (this *UserController) HandleLogin() {
	// 获取数据
	userName := this.GetString("username")
	pwd := this.GetString("pwd")
	// 校验数据
	if userName == "" || pwd == "" {
		this.Data["error"] = "登录数据不完整，请重新登录"
		this.TplName = "login.html"
		return
	}
	// 处理数据
	o := orm.NewOrm()
	var user models.User
	user.Name = userName

	err := o.Read(&user, "Name")
	if err != nil {
		this.Data["error"] = "用户名或密码错误"
		this.TplName = "login.html"
		return
	}
	if user.PassWord != pwd {
		this.Data["error"] = "用户名或密码错误"
		this.TplName = "login.html"
		return
	}
	if user.Active != true {
		this.Data["error"] = "用户未激活，请前往邮箱激活"
		this.TplName = "login.html"
		return
	}
	// 返回视图
	remember := this.GetString("remember")
	// 加密储存cookie
	if remember == "on" {
		temp := base64.StdEncoding.EncodeToString([]byte(userName))
		this.Ctx.SetCookie("userName", temp, 24*3600*30)
	} else {
		this.Ctx.SetCookie("userName", userName, -1)
	}
	// 跳转到首页
	// 1. 首页的简单显示实现
	// 2. 登录判断(路由过滤器)
	// 3. 首页显示
	// 4. 三个页面
	// 视图布局
	// 添加地址页面
	// 用户中心信息页显示
	this.SetSession("userName", userName)
	this.Redirect("/", 302)
}

// Logout 退出登录
func (this *UserController) Logout() {
	this.DelSession("userName")
	// 跳转视图
	this.Redirect("/login", 302)
}

// ShowUserCenterInfo 展示用户中心信息
func (this *UserController) ShowUserCenterInfo() {
	userName := GetUser(&this.Controller)
	// 登陆后才可以访问该函数，所以不需要验证
	// 查询地址表内容
	o := orm.NewOrm()
	// 高级查询 表关联RelatedSel 过滤条件userName Filter
	var addr models.Address
	o.QueryTable("Address").RelatedSel("User").Filter("User__Name", userName).Filter("IsDefault", true).One(&addr)
	if addr.Id == 0 {
		this.Data["addr"] = "nil"
	} else {
		this.Data["addr"] = addr
	}
	// 获取历史浏览纪律
	conn, err := redis.Dial("tcp", "192.168.8.136:6379", redis.DialPassword("12345678"))
	defer conn.Close()
	if err != nil {
		logs.Info("redis连接错误")
	}
	// 获取用户id
	var user models.User
	user.Name = userName
	o.Read(&user, "Name")
	// 获取五条数据
	rep, err := conn.Do("lrange", "history_"+strconv.Itoa(user.Id), 0, 4)
	// 回复助手函数
	goodsIDs, err := redis.Ints(rep, err)
	// 查询商品数据
	var goodsSKUs []models.GoodsSKU
	for _, value := range goodsIDs {
		var goods models.GoodsSKU
		goods.Id = value
		o.Read(&goods)
		goodsSKUs = append(goodsSKUs, goods)
	}
	this.Data["goodsSKUs"] = goodsSKUs
	this.Layout = "userCenterLayout.html"
	this.TplName = "user_center_info.html"
}

// ShowUserCenterOrder 展示用户中心订单页
func (this *UserController) ShowUserCenterOrder() {
	GetUser(&this.Controller)
	//userName := GetUser(&this.Controller)
	//o := orm.NewOrm()
	//var user models.User
	//user.Name = userName
	//o.Read(&user, "Name")
	//
	//// 获取pagecount
	//count, err := o.QueryTable("OrderInfo").RelatedSel("User").Filter("User__id", user.Id).Count()
	//if err != nil {
	//	logs.Info(err)
	//	return
	//}
	//pageSize := 2
	//pageCount := math.Ceil(float64(count) / float64(pageSize))
	//pageIndex, err := this.GetInt("pageIndex")
	//if err != nil {
	//	pageIndex = 1
	//}
	//pages := PageTool(int(pageCount), pageIndex)
	//this.Data["pages"] = pages
	//this.Data["pageIndex"] = pageIndex
	//
	//start := (pageIndex - 1) * pageSize
	//
	//// 获取上一页
	//prePage := pageIndex - 1
	//if prePage <= 1 {
	//	prePage = 1
	//}
	//this.Data["prePage"] = prePage
	//// 获取下一页
	//nextPage := pageIndex + 1
	//if nextPage > int(pageCount) {
	//	nextPage = int(pageCount)
	//}
	//this.Data["nextPage"] = nextPage
	//// 获取订单表的数据
	//var orderInfos []models.OrderInfo
	//o.QueryTable("OrderInfo").RelatedSel("User").Filter("User__Id", user.Id).Limit(pageSize, start).All(&orderInfos)
	//goodsBuffer := make([]map[string]interface{}, len(orderInfos))
	//
	//// 查询订单商品表
	//for index, orderInfo := range orderInfos {
	//	var orderGoods []models.OrderGoods
	//	o.QueryTable("OrderGoods").RelatedSel("OrderInfo", "GoodsSKU").Filter("OrderInfo__ID", orderInfo.Id).All(&orderGoods)
	//	temp := make(map[string]interface{})
	//	temp["orderInfo"] = orderInfo
	//	temp["orderGoods"] = orderGoods
	//
	//	goodsBuffer[index] = temp
	//}
	//
	//this.Data["goodsBuffer"] = goodsBuffer
	// 订单商品表
	this.Layout = "userCenterLayout.html"
	this.TplName = "user_center_order.html"
}

// ShowUserCenterSite 展示用户中心地址页
func (this *UserController) ShowUserCenterSite() {
	userName := GetUser(&this.Controller)
	//this.Data["userName"] = userName
	// 获取地址信息
	o := orm.NewOrm()
	var addr models.Address
	o.QueryTable("Address").RelatedSel("User").Filter("User__Name", userName).Filter("IsDefault", true).One(&addr)

	// 传递给视图
	this.Data["addr"] = addr

	this.Layout = "userCenterLayout.html"
	this.TplName = "user_center_site.html"
}

// HandleUserCenterSite 处理用户中心地址数据
func (this *UserController) HandleUserCenterSite() {
	// 获取数据
	receiver := this.GetString("receiver")
	addr := this.GetString("addr")
	zipCode := this.GetString("zipCode")
	phone := this.GetString("phone")
	// 校验数据
	if receiver == "" || addr == "" || zipCode == "" || phone == "" {
		logs.Info("添加数据不完整")
		this.Redirect("/user/userCenterSite", 302)
	}
	// 处理数据
	o := orm.NewOrm()
	var addrUser models.Address
	// 查询原来的默认地址
	addrUser.IsDefault = true
	err := o.Read(&addrUser, "IsDefault")
	// 添加默认地址之前需要把原来的默认地址地址更新成非默认地址
	if err == nil {
		addrUser.IsDefault = false
		o.Update(&addrUser)
	}

	// 更新默认地址时，需要给原来的地址对象id赋值
	// 关联
	userName := this.GetSession("userName")
	var user models.User
	user.Name = userName.(string)
	o.Read(&user, "Name")

	var addrUserNew models.Address
	addrUserNew.Receiver = receiver
	addrUserNew.Zipcode = zipCode
	addrUserNew.Addr = addr
	addrUserNew.Phone = phone
	addrUserNew.IsDefault = true
	addrUserNew.User = &user
	o.Insert(&addrUserNew)

	// 返回视图
	this.Redirect("/user/userCenterSite", 302)
}
